package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //检查是否有业务异常 1地址是否存在 2商品信息(购物车)是否存在
        AddressBook addressInfo = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressInfo == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        List<ShoppingCart> shoppingInfo =
                shoppingCartMapper.searchShoppingCartInfo(BaseContext.getCurrentId());
        if (shoppingInfo == null || shoppingInfo.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        //拷贝字段
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //--------------提交orders表信息----------------
        //查询 address信息 加入到orders表用冗余字段
        String address = addressInfo.getProvinceName()
                + addressInfo.getCityName()
                + addressInfo.getDistrictName()
                + addressInfo.getDetail();
        //添加地址
        orders.setAddress(address);
        //添加收货人
        orders.setConsignee(addressInfo.getConsignee());
        //设置订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //添加用户名
        //orders.setUserName(addressInfo.getuse);
        //添加用户id
        orders.setUserId(addressInfo.getUserId());
        //添加手机号
        orders.setPhone(addressInfo.getPhone());
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置订单状态
        orders.setStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);

        orderMapper.addOrder(orders);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderNumber(orders.getId().toString())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .build();

        //------------------提交order_detail表信息-菜品信息------------------
        //获得了 用户下单的商品信息

        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart info : shoppingInfo) {
            //每个依次添加 菜单id
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(info, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        //批量添加到order_detail表中
        orderDetailMapper.addDetail(orderDetails);

        //-----------销毁购物车信息-------------
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        JSONObject jsonObject = new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getOrderByNumber(outTradeNo);
        if(ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        //通过websocket向客户端发送来单提醒
        Map<String, Object> map = new HashMap();
        map.put("type", 1);// 1 来单提醒 2 客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号>: " + ordersDB.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

        orderMapper.update(orders);
    }

    @Override
    public PageResult historyOrderPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        Page<Orders> page = orderMapper.orderPage(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);

    }

    @Override
    public void reminder(Long id) {
        //  从数据库查询
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getOrderById(id);
        if(ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //通过websocket向客户端发送来单提醒
        Map<String, Object> map = new HashMap();
        map.put("type", 2);// 1 来单提醒 2 客户催单
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号>: " + ordersDB.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);


    }


}
